#ifndef XG_POSTGRESQLCONNECT_H
#define XG_POSTGRESQLCONNECT_H
//////////////////////////////////////////////////////////////
#include <libpq-fe.h>
#include "DBConnect.h"

class PostgreSQLRowData : public RowData
{
	friend class PostgreSQLQueryResult;

protected:
	bool m_bNull;
	int m_iRowNum;
	PGresult* res;

public:
	bool isNull();
	string getString(int index);
	int getDataLength(int index);
	PostgreSQLRowData(PGresult* res);
	int getData(int index, char* data, int len);
};

class PostgreSQLQueryResult : public QueryResult
{
	friend class PostgreSQLConnect;

private:
	int iCurIndex;
	int iRowCount;

protected:
	PGconn* m_pConn;
	PGresult* m_pSQLRes;

public:
	~PostgreSQLQueryResult();
	PostgreSQLQueryResult(PGresult* res, PGconn* conn);

	int rows();
	int cols();
	void close();
	sp<RowData> next();
	bool seek(int ofs);
	int getErrorCode();
	string getErrorString();
	string getColumnName(int index);
	bool getColumnData(ColumnData& data, int index);
};

class PostgreSQLConnect : public DBConnect
{
protected:
	PGconn* m_pConn;

	int bind(void* stmt, const vector<DBData*>& vec);

public:
	PostgreSQLConnect();
	~PostgreSQLConnect();

	void close();
	bool commit();
	bool rollback();
	const char* getSystemName();
	bool begin(bool commited = true);
	int getTables(vector<string>& vec);
	bool setCharset(const string& charset);
	int getPrimaryKeys(vector<string>& vec, const string& tabname);
	bool connect(const string& host, int port, const string& name, const string& user, const string& password);

	int getErrorCode();
	string getErrorString();
	int execute(const string& sqlcmd);
	sp<QueryResult> query(const string& sqlcmd);
	int execute(const string& sqlcmd, const vector<DBData*>& vec);
	sp<QueryResult> query(const string& sqlcmd, const vector<DBData*>& vec);

public:
	static bool Setup();
};
//////////////////////////////////////////////////////////////
#endif